using System;
using System.Collections.Generic;

namespace Be.Timvw.Framework
{
    public static class TypeHelper
    {
        private static readonly Dictionary<string, string> s_CsharpTypeNames;

        static TypeHelper()
        {
            s_CsharpTypeNames = new Dictionary<string, string>();
            s_CsharpTypeNames.Add("System.SByte", "sbyte");
            s_CsharpTypeNames.Add("System.Int16", "short");
            s_CsharpTypeNames.Add("System.Int32", "int");
            s_CsharpTypeNames.Add("System.Int64", "long");
            s_CsharpTypeNames.Add("System.Byte", "byte");
            s_CsharpTypeNames.Add("System.UInt16", "ushort");
            s_CsharpTypeNames.Add("System.UInt32", "uint");
            s_CsharpTypeNames.Add("System.UInt64", "ulong");
            s_CsharpTypeNames.Add("System.Decimal", "decimal");
            s_CsharpTypeNames.Add("System.Single", "float");
            s_CsharpTypeNames.Add("System.Object", "object");
            s_CsharpTypeNames.Add("System.Boolean", "bool");
            s_CsharpTypeNames.Add("System.Char", "char");
            s_CsharpTypeNames.Add("System.String", "string");
        }

        public static string GetCsharpTypeName(Type type)
        {
            string typeName = type.FullName;
            if(typeName.EndsWith("&"))
            {
                typeName = typeName.Substring(0, typeName.Length - 1);
            }

            string cSharpTypeName;
            if(s_CsharpTypeNames.TryGetValue(typeName, out cSharpTypeName))
            {
                return cSharpTypeName;
            }

            return typeName;
        }

        public static Type[] Sort(Type[] types)
        {
            Array.Sort(types, CompareTypes);
            return types;
        }

        public static int CompareTypes(Type type1, Type type2)
        {
            if(type1.Assembly.FullName != type2.Assembly.FullName)
            {
                return type1.Assembly.FullName.CompareTo(type2.Assembly.FullName);
            }

            if(type1.Namespace != type2.Namespace)
            {
                return type1.Namespace.CompareTo(type2.Namespace);
            }

            return type1.FullName.CompareTo(type2.FullName);
        }
    }
}